import type { Request, Response } from 'express';
import { parse } from 'url';

import type { ExgItem, ExgTableListParams, EmsItem } from './data.d';

const getEmgList = () => {
  const tableListDataSource: ExgItem[] = [];
  for (let i = 0; i < 21; i++) {
    tableListDataSource.push({
      preNo: 'wqqqq',
      gNo: i.toString(),
      copGNo: i.toString(),
      materialsProperties: '成品',
      codeTs: `2009110000${i}`,
      gName: `冷冻的橙汁${i}`,
      gModel: '罐',
      unit: '罐',
      unit1: '千克',
      unit2: '千克',
      decPrice: '50',
      curr: '人民币',
      modifyMark: '未修改',
    });
  }
  return tableListDataSource;
};

const tableListDataSource: ExgItem[] = getEmgList();

function getEmg(req: Request, res: Response, u: string) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }
  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query as unknown as ExgTableListParams;

  let dataSource = [...tableListDataSource].slice(
    ((current as number) - 1) * (pageSize as number),
    (current as number) * (pageSize as number),
  );
  if (params.sorter) {
    const sorter = JSON.parse(params.sorter as any);
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach((key) => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }
          return;
        }
        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }
  if (params.filter) {
    const filter = JSON.parse(params.filter as any) as Record<string, string[]>;
    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter((item) => {
        return Object.keys(filter).some((key) => {
          if (!filter[key]) {
            return true;
          }
          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }
          return false;
        });
      });
    }
  }

  let finalPageSize = 10;
  if (params.pageSize) {
    finalPageSize = parseInt(`${params.pageSize}`, 10);
  }

  const result = {
    data: dataSource,
    total: tableListDataSource.length,
    success: true,
    pageSize: finalPageSize,
    current: parseInt(`${params.current}`, 10) || 1,
  };

  return res.json(result);
}

function getEmgDetail(req: Request, res: Response, u: string) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }
  const data = {
    preNo: 'wqqqq',
    gNo: 1,
    copGNo: 1,
    materialsProperties: '成品',
    codeTs: `2009110000`,
    gName: `冷冻的橙汁`,
    gModel: '罐',
    unit: '罐',
    unit1: '千克',
    unit2: '千克',
    decPrice: '50',
    curr: '人民币',
    modifyMark: '未修改',
  };

  const result = {
    data,
    success: true,
  };
  return res.json(result);
}

const getEmsList = () => {
  const emsListDataSource: EmsItem[] = [];
  for (let i = 0; i < 21; i++) {
    emsListDataSource.push({
      preNo: `20100180111${i}`,
      workNo: `20100180111${i}`,
      emsNo: `H010018A045${i}`,
      declareType: '备案申请',
      approveStatus: '1',
      customsCode: `黄埔海关`,
      emsClass: `2|H账册`,
      endDate: '2018-08-30 21:49:49',
      tradeCode: '1100696075',
      tradeName: '北京世纪周峰商业设备有限公司',
      inputTime: '2018-08-30 21:49:49',
      declareDate: '2018-08-30 21:49:49',
      approveDate: '2018-08-30 21:49:49',
    });
  }
  return emsListDataSource;
};

const emsListDataSource: EmsItem[] = getEmsList();

function getEms(req: Request, res: Response, u: string) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }
  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query;

  let dataSource = [...emsListDataSource].slice(
    ((current as number) - 1) * (pageSize as number),
    (current as number) * (pageSize as number),
  );
  if (params.sorter) {
    const sorter = JSON.parse(params.sorter as any);
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach((key) => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }
          return;
        }
        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }
  if (params.filter) {
    const filter = JSON.parse(params.filter as any) as Record<string, string[]>;
    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter((item) => {
        return Object.keys(filter).some((key) => {
          if (!filter[key]) {
            return true;
          }
          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }
          return false;
        });
      });
    }
  }

  let finalPageSize = 10;
  if (params.pageSize) {
    finalPageSize = parseInt(`${params.pageSize}`, 10);
  }

  const result = {
    data: dataSource,
    total: emsListDataSource.length,
    success: true,
    pageSize: finalPageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };

  return res.json(result);
}

export default {
  'GET /api/ems': getEms,
  'GET /api/emg': getEmg,
  'GET /api/emgDetail': getEmgDetail,
};
